package controllers

import (
	"encoding/json"
	"errors"
	"qysoft/libs/encrypt"

	// "reflect"
	"qysoft/models"
	// "strconv"
	"strings"
	"time"

	"github.com/astaxie/beego"
)

// ResourceController oprations for Resource
type ResourceController struct {
	CommonController
}

// URLMapping 方法映射
func (c *ResourceController) URLMapping() {
	c.Mapping("Post", c.Post)
	c.Mapping("GetOne", c.GetOne)
	c.Mapping("GetAll", c.GetAll)
	c.Mapping("Update", c.Update)
	c.Mapping("Delete", c.Delete)
	//	c.Mapping("GetResourceList", c.GetResourceList)
	//	c.Mapping("DeleteResources", c.DeleteResources)
	//	c.Mapping("GetAllResources", c.GetAllResources)
}

// Post create Resource
// @Title 新增资源
// @Description create Resource
// @Param	body		body 	models.Resource	true		"body for Resource content"
// @Success 201 {int} models.Resource
// @Failure 403 body is empty
// @router / [post]
func (c *ResourceController) Post() {
	var v models.Resource
	user := c.User
	// rdata, err := c.AesDecode(c.GetString("tdata"))
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	err = json.Unmarshal(rdata, &v)
	// v.Name, _ = sdata["Name"].(string)
	// v.Url, _ = sdata["Url"].(string)
	// v.Remark, _ = sdata["Remark"].(string)
	// v.Logo, _ = sdata["Logo"].(string)
	// v.Pid = sdata["Pid"].(string)
	// vlevel, _ := sdata["Level"].(string)
	// vtype, _ := sdata["Type"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Status, _ = strconv.Atoi(vstatus)
	// //	v.Pid, _ = strconv.Atoi(vpid, 10, 64)
	// v.Level, _ = strconv.Atoi(vlevel)
	// v.Type, _ = strconv.Atoi(vtype)
	v.Seq = 100
	v.Isdelete = 0
	v.Status = 1
	v.Creater = user.Name
	v.Ctime = time.Now()
	v.Updater = v.Creater
	v.Utime = v.Ctime
	v.Id = encrypt.GetGuid()
	_, err = models.AddResource(&v)
	if err != nil {
		c.RetError(ErrDatabase)
	}

	c.Dlog("添加了系统资源", v.Id)

	c.RetSuccess(v)
}

// GetOne 获取一个资源
// @Title 获取一个资源
// @Description get Resource by id
// @Param	id		path 	string	true		"The key for staticblock"
// @Success 200 {object} models.Resource
// @Failure 403 :id is empty
// @router /:id [get]
func (c *ResourceController) GetOne() {
	id := c.GetString(":id")
	v, err := models.GetResourceById(id)
	if err != nil {
		c.RetError(ErrNoData)
	}
	c.RetSuccess(v)
}

// GetAll  获取所有资源列表
// @Title 获取所有资源列表
// @Description get Resource
// @Param	query	query	string	false	"Filter. e.g. col1:v1,col2:v2 ..."
// @Param	fields	query	string	false	"Fields returned. e.g. col1,col2 ..."
// @Param	sortby	query	string	false	"Sorted-by fields. e.g. col1,col2 ..."
// @Param	order	query	string	false	"Order corresponding to each sortby field, if single value, apply to all sortby fields. e.g. desc,asc ..."
// @Param	limit	query	string	false	"Limit the size of result set. Must be an integer"
// @Param	offset	query	string	false	"Start position of result set. Must be an integer"
// @Success 200 {object} models.Resource
// @Failure 403
// @router / [get]
func (c *ResourceController) GetAll() {
	var fields []string
	var sortby []string
	var order []string
	query := make(map[string]string)
	var limit int64 = -1
	var offset int64

	// fields: col1,col2,entity.col3
	if v := c.GetString("fields"); v != "" {
		fields = strings.Split(v, ",")
	}
	// limit: 10 (default is 10)
	if v, err := c.GetInt64("limit"); err == nil {
		limit = v
	}
	// offset: 0 (default is 0)
	if v, err := c.GetInt64("offset"); err == nil {
		offset = v
	}
	// sortby: col1,col2
	if v := c.GetString("sortby"); v != "" {
		sortby = strings.Split(v, ",")
	}
	// order: desc,asc
	if v := c.GetString("order"); v != "" {
		order = strings.Split(v, ",")
	}
	// query: k:v,k:v
	if v := c.GetString("query"); v != "" {
		for _, cond := range strings.Split(v, ",") {
			kv := strings.SplitN(cond, ":", 2)
			if len(kv) != 2 {
				c.Data["json"] = errors.New("Error: invalid query key/value pair")
				c.ServeJSON()
				return
			}
			k, v := kv[0], kv[1]
			query[k] = v
		}
	}
	sortby = append(sortby, "Pid")
	order = append(order, "asc")
	l, err := models.GetAllResource(query, fields, sortby, order, offset, limit)
	if err != nil {
		beego.Error("err is :", err)
		c.RetError(ErrDatabase)
	} else {
		c.RetSuccess(l)
	}

}

// Update 更新资源
// @Title 更新资源
// @Description update the Resource
// @Param	id		path 	string	true		"The id you want to update"
// @Param	body		body 	models.Resource	true		"body for Resource content"
// @Success 200 {object} models.Resource
// @Failure 403 :id is not int
// @router /Update [post]
func (c *ResourceController) Update() {
	user := c.User
	// ee, err := c.AesDecode(c.GetString("tdata"))
	// if err != nil {
	// 	c.RetError(ErrToken)
	// }
	// sdata, _ := ee.(map[string]interface{})
	// id := sdata["Id"].(string)
	rdata, err := c.AesDecodeToByte(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	var v models.Resource
	err = json.Unmarshal(rdata, &v)
	if err != nil {
		c.RetError(ErrInputData)
	}
	//	id, _ := strconv.ParseInt(sid, 10, 64)
	u, _ := models.GetResourceById(v.Id)
	// v = &u
	// v.Name, _ = sdata["Name"].(string)
	// v.Url, _ = sdata["Url"].(string)
	// v.Remark, _ = sdata["Remark"].(string)
	// v.Logo, _ = sdata["Logo"].(string)
	// vseq, _ := sdata["Seq"].(string)
	// v.Pid = sdata["Pid"].(string)
	// vlevel, _ := sdata["Level"].(string)
	// vtype, _ := sdata["Type"].(string)
	// vstatus, _ := sdata["Status"].(string)
	// v.Status, _ = strconv.Atoi(vstatus)
	// //	v.Pid, _ = strconv.ParseInt(vpid, 10, 64)
	// v.Level, _ = strconv.Atoi(vlevel)
	// v.Type, _ = strconv.Atoi(vtype)
	// v.Seq, _ = strconv.Atoi(vseq)

	v.Updater = user.Name
	v.Utime = time.Now()
	if err := models.UpdateResourceById(&v); err == nil {
		c.Dlog("修改了系统资源,资源id为：", v.Id, 1, u)
		c.RetSuccess(v.Id)
	}
	c.RetError(ErrDatabase)

}

// Delete 删除资源
// @Title 删除资源
// @Description delete the Resource
// @Param	id		path 	string	true		"The id you want to delete"
// @Success 200 {string} delete success!
// @Failure 403 id is empty
// @router /Delete [post]
func (c *ResourceController) Delete() {
	user := c.User
	rdata, err := c.AesDecode(c.GetString("tdata"))
	if err != nil {
		c.RetError(ErrToken)
	}
	sdata, _ := rdata.(map[string]interface{})
	id := sdata["Id"].(string)
	//	id, err := strconv.ParseInt(sid, 10, 64)
	if err != nil {
		c.RetError(ErrInputData)
	}
	if rs, err := models.GetResourceByPid(id); err == nil && len(rs) > 0 {
		c.Data["json"] = "不允许删除有子资源的资源！"
		c.RetError(ErrPid)
	}
	if err := models.SoftDeleteResource(id, user.Name); err == nil {
		c.Dlog("删除了系统资源", id)
		rt := make(map[string]interface{})
		rt["Id"] = id
		c.RetSuccess(rt)
	}
	c.RetError(ErrDatabase)
}
